<?php
/*
 * IKPHP 爱客开源社区 @copyright (c) 2012-3000 IKPHP All Rights Reserved 
 * @author 小麦
 * @Email:ikphp@sina.cn 2014年8月27日16:58:00
 * @小组应用
 */
namespace IKPHP\Apps\Group\Controllers;

use IKPHP\Apps\Group\Controllers;
use IKPHP\Common\Models\User;
use IKPHP\Apps\Group\Models\Group;
use IKPHP\Apps\Group\Models\GroupCate;
use IKPHP\Apps\Group\Models\GroupUsers;
use IKPHP\Apps\Group\Models\GroupTopics;
use IKPHP\Common\Models\Images;

use IKPHP\Common\Models\LikeModel;


class TopicController extends GroupBaseController
{
	private $userid = 0;
	
    public function initialize()
    {
        parent::initialize();
        // 访问者控制
		if ($this->visitor){
			$this->userid = $this->visitor['userid'];
		}        
    }
    //发布帖子
    public function addAction($id=''){
    	//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;
		// 是否加入
		$isGroupUser = GroupUsers::isGroupUser ( $this->userid, $id );
		if (! $isGroupUser) {
			return $this->error ( '只有小组成员才能发言，请先加入小组!' );
		}
		// 获取小组信息
		$strGroup = Group::getOneGroup ( $id );
		// 审核
		if ($strGroup ['isaudit'] == 1) return $this->error ( '该小组还在审核中，暂时还不能发帖！' );				
		//查询预先数据
		$strTopic = GroupTopics::findFirst("userid='$userid' and groupid = '0' and title = '0'");
    	if(!$strTopic){
			//新增一条
			$data['userid'] = $userid;
			$data['typeid'] = '0';
			$data['groupid'] = '0';
			$data['title'] = '0';
			$data['addtime'] = time();
			$data['uptime'] = time();
			$strTopic = new GroupTopics(); 
			$newTopic = $strTopic->create($data);  
			$topicid = $strTopic->topicid;
			$this->assign('isold', false);
			$arrPhotos = array();			
		}else{
			$this->assign('isold', true);
			$topicid = $strTopic->topicid;
			//浏览该照片
			$type = 'topic';
			$arrPhotos = Images::getImagesByTypeid($type, $topicid);
		}
		$this->assign('groupid',$id);	 

		$this->assign('arrPhotos',$arrPhotos);
		
		$this->assign('strTopic',$strTopic);
    	$this->_config_seo ( array ('title' => $strGroup ['groupname'] . '新话题', 'subtitle' => '小组' ) );	
    }
    //编辑帖子
    public function editAction($topicid=''){
     	//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;  
    		
		if(!is_numeric($topicid) || empty($topicid)){
			return $this->error('呃...你想访问的页面不存在');
		}		 	
		
		$strTopic = GroupTopics::findFirst("topicid = '$topicid'");
		
		if($strTopic && $strTopic->userid == $userid){				
			//浏览该照片
			$type = 'topic';
			$arrPhotos = Images::getImagesByTypeid($type, $topicid);
			$this->assign('arrPhotos',$arrPhotos);
			
			$this->assign('groupid', $strTopic->groupid);
			$this->assign('strTopic',$strTopic);
			$this->_config_seo ( array ('title' => '编辑“' . $strTopic->title . '”', 'subtitle' => '小组_' . C ( 'ik_site_title' ), 'keywords' => '', 'description' => '' ) );			
		}else{
			return $this->error ( "您没有权限编辑帖子！" );
		}
    } 
    //更新帖子
    public function updateAction($groupid=''){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
    		
		if(!is_numeric($groupid) || empty($groupid)){
			return $this->error('呃...你想访问的页面不存在');
		}			    	
    	if (IS_POST){
			$userid = $this->userid;
			
			$topicid = $data['topicid'] = $this->_post ( 'topicid' );
			$title   = $data['title'] = $this->_post ( 'title' );
			$content = $data['content'] = $this->_post ( 'content' );
			$isreply = $data['isreply'] = $this->_post ( 'isreply','intval', 0); // 是否允许评论

			if ($this->security->checkToken()) {
				// 是否加入 修改bug漏洞表单提交 2013-6-28
				$isGroupUser = GroupUsers::isGroupUser ( $this->userid, $groupid );
				if (! $isGroupUser) {
					return $this->error ( '只有小组成员才能发言，请先加入小组!' );
				}
				//是否是自己发的
				$strTopic = GroupTopics::findFirst("userid='$userid' and topicid = '$topicid' ");				
				if (!$strTopic) {
					return $this->error ( '非法操作；请不要搞怪!' );
				}
						
				if ($title == '') {
					return $this->error ( '不要这么偷懒嘛，标题不允许为空' );
				}else if(ck_strlen($title) < 2){
					return $this->error ( '不要这么偷懒嘛，标题写的太少了' );
				} else if ($content == '') {
					return $this->error ( '没有任何内容是不允许你通过滴^_^' );
				} elseif (ck_strlen($content) > 20000) {
					return $this->error('内容太长了已经超出2万字啦！');
				}
								
				//更新是否有图片
				$arrimg = ikhtml_img('topic',$topicid,$content); 
				count($arrimg) > 0 ? $data['isphoto']= 1 : $data['isphoto']= 0;
				
				//开始更新
				$data['uptime'] = time();
				$data['groupid'] = $groupid;
				$is_save = $strTopic->save($data);
				if($is_save){
						/////////////执行更新图片信息/////////////
						$arrSeqid = $this->_post('seqid');
						$arrTitle = $this->_post('photodesc');
						if(is_array($arrSeqid)){
							foreach($arrSeqid as $key=>$item){
								$seqid = $arrSeqid[$key];
								$imgtitle = empty($arrTitle[$key]) ? '' : $arrTitle[$key];
								$layout = $this->_post ( 'layout_'.$seqid);
								$dataimg = array('title'=>$imgtitle, 'align'=> $layout,'typeid'=>$topicid);
								$where = "type = 'topic' and typeid='$topicid' and seqid = '$seqid'";
								Images::updateImage($dataimg,$where);
							}
						}
						/////////////执行更新图片信息结束//////////////////
						
						return $this->_redirect('group/topic/'.$topicid);						
				}else{
					return $this->error('呃...操作失败了');
				}
				
			}else{
				return $this->error ( '呃...已经超时了' );
			}
			
    	}else{
    		return $this->error('呃...你没有权限访问这个页面');
    	}
    }   
    //显示帖子
    public function showAction($id = 0 ,$page = 1){
		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
		$strTopic = GroupTopics::getOneTopic ( $id );
		if(empty($strTopic)) return $this->error ( '呃...你想要的东西不在这儿' );
		// 小组信息
		$strGroup = Group::getOneGroup ( $strTopic ['groupid'] );		
		$strTopic ['user'] = User::getOneUser ( $strTopic ['userid'] );
		
		//上一篇帖子
		$upTopic   = GroupTopics::findFirst("topicid < '$id' AND groupid = ".$strTopic['groupid']);
		//下一篇帖子
		$downTopic = GroupTopics::findFirst("topicid > '$id' AND groupid = ".$strTopic['groupid']);
		$strTopic['upTopic'] = !$upTopic ? '':$upTopic->toArray();
		$strTopic['downTopic'] = !$downTopic ? '':$downTopic->toArray();

		// 是否已经加入
		$isGroupUser = GroupUsers::isGroupUser ( $this->userid, $strTopic ['groupid'] );		
		$this->assign ( 'isGroupUser', $isGroupUser );

    			
		//浏览数+1
		if($this->userid != $strTopic['userid']){
			GroupTopics::findFirst("topicid = '$id'")->save(array('count_view'=>$strTopic['count_view']+1));
		}		
		
		//获取评论 类型type 类型ID typeid 返回的连接
		$order    = $this->_get('order','trim','asc');
		$isauthor = $this->_get('isauthor','trim', 0);		
		$this->assign('params', array(
						'type'=>'GroupTopics',
						'typeid'=>$id,
						'userid'=>$strTopic['userid'], 
						'link'=>'group/topic',
						'order'=>$order,
						'isauthor'=>$isauthor,
						'page'=>$page
		));
		//评论list结束

		//sns组件开始
		$this->assign('snsparams', array(
						'type'=>'GroupTopics',
						'typeid'=>$id,
						'userid'=>$strTopic['userid'], 
						'title' =>$strTopic['title'],
						'content' =>sub_str(clearText($strTopic['content']),260),
						'href'  =>'group/topic/'.$id,
						'headimg'  =>$strTopic['headimg'],
						'count_recommend'  =>$strTopic['count_recommend'],
						'count_like'  =>$strTopic['count_like'],		
						'link'=>'group/topic',
						'page'=>$page
		));
		//sns end		
		
		//操作箱
		$arrOption =  array();
		$arrOption ['istop'] = $strTopic ['istop'] == 0 ? '置顶' : '取消置顶';
		$arrOption ['isdigest'] = $strTopic ['isdigest'] == 0 ? '精华' : '取消精华';
		$arrOption ['isshow'] = $strTopic ['isshow'] == 0 ? '隐藏' : '显示';	
		$arrOption ['isreply'] = $strTopic ['isreply'] == 0 ? '禁止回应' : '允许回应';	
			
		$this->assign('arrOption',$arrOption);
		
		// 喜欢该帖子的用户
		$arrCollectUser = LikeModel::getLikeUser($id, 'GroupTopics', 12);
		$this->assign ( 'arrCollectUser', $arrCollectUser );
		// 最新话题
		$newTopic = GroupTopics::getNewTopic ( $strTopic ['groupid'], 6 );		
		$this->assign ( 'newTopic', $newTopic );

    		
		//帖子浏览量加 +1
		if ($strTopic ['userid'] != $this->userid) {
			GroupTopics::findFirst("topicid = '$id'")->update(array('count_view'=>$strTopic['count_view']+1));
		}
				
		$this->assign ( 'strTopic', $strTopic );
		$this->assign ( 'strGroup', $strGroup );
		$this->assign('page',$page);
		
		$this->_config_seo ( array (
				'title' => $strTopic['title'],
				'subtitle'=> $strGroup ['groupname'] . '_' . C ( 'ik_site_title' ),
				'keywords' => ikscws ( $strTopic ['title'] ),
				'description'=> sub_str(clearText($strTopic['content']),200), 
		) );		
    } 
    //操作帖子
    public function operationAction($id = ''){
     	//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;  
		    	
		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
		
		$op = $this->_get('op');
		
		$strTopic = GroupTopics::getOneTopic ( $id );
		if(empty($strTopic)) return $this->error ( '呃...你想要的东西不在这儿' );
		$strGroup = Group::getOneGroup( $strTopic ['groupid'] );
		
		if(!empty($op)){
			switch ($op) {
					case "istop" :
								$istop = $strTopic ['istop'];
								$istop == 0 ? $istop = 1 : $istop = 0;

								//只有组长可以置顶帖子
								if ($userid == $strGroup ['userid']) {
									GroupTopics::findFirst("topicid = '$id'")->save(array('istop'=>$istop));
									return $this->_redirect ( 'group/topic/'.$id );
								} else {
									return $this->error ( "只有小组组长才能置顶帖子" );
								}								
						break;
						
					case "isdigest" :
								$isdigest = $strTopic ['isdigest'];
								$isdigest == 0 ? $isdigest = 1 : $isdigest = 0;

								//只有组长可以
								if ($userid == $strGroup ['userid']) {
									GroupTopics::findFirst("topicid = '$id'")->save(array('isdigest'=>$isdigest));
									return $this->_redirect ( 'group/topic/'.$id );
								} else {
									return $this->error ( "只有小组组长才能设置精华帖" );
								}						
						break;
						
					case "isshow" :
								$isshow = $strTopic ['isshow'];
								$isshow == 0 ? $isshow = 1 : $isshow = 0;

								//只有组长可以
								if ($userid == $strGroup ['userid']) {
									GroupTopics::findFirst("topicid = '$id'")->save(array('isshow'=>$isshow));
									return $this->_redirect ( 'group/topic/'.$id );
								} else {
									return $this->error ( "只有小组组长才能设是否显示" );
								}						
						break;
						
					case "isreply" :
								$isreply = $strTopic ['isreply'];
								$isreply == 0 ? $isreply = 1 : $isreply = 0;

								//只有组长可以
								if ($userid == $strGroup ['userid']) {
									GroupTopics::findFirst("topicid = '$id'")->save(array('isreply'=>$isreply));
									return $this->_redirect ( 'group/topic/'.$id );
								} else {
									return $this->error ( "你没有权限设置是回应" );
								}
						break;	
						
					case "delete" :
								//只有组长和自己的帖子
								if ($userid == $strGroup ['userid'] || $userid==$strTopic['userid']) {
									GroupTopics::findFirst("topicid = '$id'")->delete();
									return $this->_redirect ( 'group/show/'.$strTopic['groupid'] );
								} else {
									return $this->error ( "你没有权限设置是回应" );
								}						
						break;	
																	
					default:
						return $this->error('呃...无效的操作');
			
			}
		}else{
			return $this->error('呃...你想访问的页面不存在');
		} 
    }   
    /**
     * 贴新闻
     * @param int id 分类id
     **/
    public function addnewsAction($id = ''){
    	//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;
		// 是否加入
		$isGroupUser = GroupUsers::isGroupUser ( $this->userid, $id );
		if (! $isGroupUser) {
			return $this->error ( '只有小组成员才能贴新闻，请先加入小组!' );
		}
		// 获取小组信息
		$strGroup = Group::getOneGroup ( $id );
		// 审核
		if ($strGroup ['isaudit'] == 1) return $this->error ( '该小组还在审核中，暂时还不能发帖！' );	  

		if (IS_POST && $this->security->checkToken()){
			
			$link = $this->_post('url');
			$title = $this->_post('title');
			$content= $this->_post('content');
			$data ['tag'] = $this->_post ( 'tag', 'strip_tags,trim' );
			$tags = str_replace ( ' ', ' ', $data ['tag'] );
			$arrtag = explode ( ' ', $tags );
			
			//输入检查
			if(empty($link)){
				return $this->error ( '要抓取的网站链接不能为空' );
			}
					
			if(empty($tags)){
				return $this->error ( '内容标签不能为空' );
			}
					
			if(empty($title)){
				return $this->error ( '标题不能没有啊' );
			}			

			if(empty($content)){
				return $this->error ( '内容部允许为空的' );
			}	
			
			if (ck_strlen($content) > 20000) {
				return $this->error('内容太长了已经超出2万字啦！');
			}			

			//开始入库
			
		}	
		
		$this->assign('strGroup', $strGroup);
		$this->_config_seo ( array (
				'title' => '贴链接',
				'subtitle'=> '_' . C ( 'ik_site_title' ),
				'description'=> '', 
		) );
				
    }
    //抓取新闻
    public function parseurlAction()
    {
    	$link = $this->_post('url');
    	//输入检查
		if(empty($link)){
			$jsonData = array('r'=>1,'html'=>'要抓取的网站链接不能为空');
			return $this->ajaxReturn($jsonData);
		}
		
		//不规则自动加上http
		if(!preg_match('/^http:\/\//i', $link)){
			$link = 'http://'.$link;
		}
		
		//查看远程链接是否有效

		//开始抓取
		require COM_PATH.'Functions/RobotFun.php';
		$data = getUrlFile($link);

		if(empty($data['title'])){
			$jsonData = array('r'=>1,'html'=>'要抓取网站内容失败');
			return $this->ajaxReturn($jsonData);		
		}

		$remoteData['lead_image_url'] = $data['lead_image_url'];
		$remoteData['title'] = $data['title'];
		$remoteData['content'] = strip_tags($data['content']);
		$jsonData = array('r'=>0,'data'=>$remoteData);
		return $this->ajaxReturn($jsonData);   
    }
}